(function () {


    layui.use(['layim', 'upload'], function (layim) {
        var websocket = null;
        if ('WebSocket' in window) {
            websocket = new WebSocket('ws://localhost:8080/work/webSocket/' + usercache.id);
        } else {
            alert('该浏览器不支持websocket');
        }
        websocket.onopen = function (event) {
        }
        websocket.onclose = function (event) {
        }
        websocket.onmessage = function (event) {
            var result = JSON.parse(event.data);
            if (result.id != 0) {
                //接受消息（如果检测到该socket）
                layim.getMessage({
                    username: result.userName
                    , avatar: "../photo/get/" + result.userId
                    , id: result.id
                    , type: "friend"
                    , content: result.content
                });
            }
        }
        websocket.onerror = function (event) {
        }
        window.onbeforeunload = function (event) {
            websocket.close();
        }
        function sendmessage(message) {
            websocket.send(message);
        }

        function listOneChat(id) {
            workUtils.ajaxGet("../chat/listchat", {
                limit: 10,
                page: 1,
                id: id
            }, function (data) {
                var cache = layui.layim.cache();
                var local = layui.data('layim')[cache.mine.id]; //获取当前用户本地数据
                local.chatlog["friend" + id] = data.data.reverse();
                layui.data('layim', {
                    key: cache.mine.id
                    , value: local
                });
            });
        }

        function listUnreadChat() {
            workUtils.ajaxGet("../chat/listUnreadChat", {}, function (data) {
                var userId = usercache.id;
                for (var i = 0; i < data.length; i++) {
                    var item = data[i];
                    if (userId == item.userId) {
                        //接受消息（如果检测到该socket）
                        layim.getMessage({
                            username: item.toUserName
                            , avatar: "../photo/get/" + item.toUserId
                            , id: item.id
                            , type: "friend"
                            , content: item.content
                        });
                        listOneChat(item.id);
                    } else if (userId == item.toUserId) {
                        //接受消息（如果检测到该socket）
                        layim.getMessage({
                            username: item.userName
                            , avatar: "../photo/get/" + item.userId
                            , id: item.id
                            , type: "friend"
                            , content: item.content
                        });
                        listOneChat(item.id);
                    }
                }
            });
        }


        //基础配置
        layim.config({
            //初始化接口
            init: {
                url: '../chat/list'
                , data: {}
            }

            //上传图片接口
            , uploadImage: {
                url: '../chat/upload/image' //（返回的数据格式见下文）
                , type: 'post' //默认post
            }

            //上传文件接口
            , uploadFile: {
                url: '../chat/upload/file' //（返回的数据格式见下文）
                , type: 'post' //默认post
            }

            //扩展工具栏
            , tool: [{
                alias: 'code'
                , title: '代码'
                , icon: '&#xe64e;'
            }]

            , brief: false //是否简约模式（若开启则不显示主面板）

            , title: '<i class="layui-icon" style="font-size: 40px;color: #009688;">&#xe611;</i> ' //自定义主面板最小化时的标题
            , right: '0px' //主面板相对浏览器右侧距离
            //,minRight: '90px' //聊天面板最小化时相对浏览器右侧距离
            , initSkin: '5.jpg' //1-5 设置初始背景
            //,skin: ['aaa.jpg'] //新增皮肤
            , isfriend: true //是否开启好友
            , isgroup: false //是否开启群组
            , min: true //是否始终最小化主面板，默认false
            , notice: true //是否开启桌面消息提醒，默认false
            , voice: false //声音提醒，默认开启，声音文件为：default.wav
            , chatLog: '../chat/chatlog' //聊天记录页面地址，若不开启，剔除该项即可

        });

        //监听自定义工具栏点击，以添加代码为例
        layim.on('tool(code)', function (insert) {
            layer.prompt({
                title: '插入代码'
                , formType: 2
                , shade: 0
            }, function (text, index) {
                layer.close(index);
                insert('[pre class=layui-code]' + text + '[/pre]'); //将内容插入到编辑器
            });
        });

        //监听layim建立就绪
        layim.on('ready', function (res) {
            layim.msgbox(5); //模拟消息盒子有新消息，实际使用时，一般是动态获得
            listUnreadChat();
        });

        var sendMsg = function (id, msg) {
            var cache = layui.layim.cache();
            var local = layui.data('layim')[cache.mine.id]; //获取当前用户本地数据

            $.ajax({
                url: '../chat/item',
                async: false,
                type: 'post',
                dateType: 'json',
                data: {"id": id, "content": msg},
                success: function (result) {
                    /*sendmessage("@"+id+"@"+msg);*/
                }
            });
        };

        //监听发送消息
        layim.on('sendMessage', function (data) {
            var To = data.to;
            var mine = data.mine;
            sendMsg(To.id, mine.content)


        });

        //监听聊天窗口的切换
        layim.on('chatChange', function (res) {
            var type = res.data.type;

            if (type === 'friend') {
                //模拟标注好友状态
            } else if (type === 'group') {
                //模拟系统消息
            }
        });


    });
})();